package com.woniuxy.carrental.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.carrental.entity.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author author
 * @create 2021-09-30 15:17
 */
@Slf4j
@Component
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        log.info(">>>>>preHandle");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-control-Allow-Origin", req.getHeader("Origin"));
        res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        res.setHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            log.info(">>>>>MyFormAuthenticationFilter---OPTIONS");
            //res.setStatus(HttpStatus.OK.value());
            res.setStatus(HttpStatus.NO_CONTENT.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            //运行访问
            super.isAccessAllowed(request, response, mappedValue);
        } catch (Exception e) {
            //出现异常，就是不许访问，后端给前端JSON信息
            HttpServletResponse res = (HttpServletResponse) response;
            res.setContentType("text/html;charset=utf-8");
            try {
                new ObjectMapper().writeValue(response.getWriter(),
                        new ResponseResult(null, 401, "先登录"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return true;
    }
}
